<template>
  <CommonDialog v-model="visible" title="编辑知识库" :width="500"
    @submit="submit" @cancel="cancel">
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="100">
      <FormItem label="名称" prop="name">
        <Input v-model="formData.name" placeholder="请输入名称" />
      </FormItem>

      <FormItem label="描述">
        <Input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入描述" />
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { onMounted, ref, inject } from 'vue'
import { Message } from 'view-ui-plus'

import { myKnowledge } from '@/api/modules/knowledgeBase'

const emit = defineEmits(['cancel', 'submit'])

const props = defineProps({
  details: Object
})

const homeUpdate = inject('homeUpdate')
// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  name: props.details.name, //名称
  description: props.details.description
})

// 表单校验条件
const rules = ref({
  name: [
    { required: true, message: '请填写名称', trigger: 'blur' },
    { required: true, message: '知识库名称已存在', trigger: 'blur', validator: async (row, val, callback) => {
      if(props.details.name === val) return callback()

      const data = await myKnowledge.check({
        data: {
          name: val
        }
      })

      if(data.status === 'OK') {
        return callback()
      }
      callback(new Error())
    } }
  ]
})

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    await myKnowledge.cateEdit({
      data: {
        ...formData.value,
        id: props.details.id
      }
    })

    Message.success('操作成功')
    homeUpdate()
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  emit('cancel')
}
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}

::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>